﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CardRegister : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strConnString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection Connection = new SqlConnection(strConnString); //establish database connection
        Session["ConnDB"] = Connection;
    }

    protected void PreviousButton_Click(object sender, EventArgs e)
    {
        System.Web.Security.Membership.DeleteUser(Request.QueryString["userName"], true); //fule kod, just as fix at the moment
        Response.Redirect("RegisterControl.aspx"); 
    }

    protected void confirmButton_Click(object sender, EventArgs e) 
    {
        SqlConnection Connection = (SqlConnection)Session["ConnDB"];

        DateTime expiry = new DateTime(Convert.ToInt32(expireYearList.SelectedValue),Convert.ToInt32(expireMonthList.SelectedValue),1); //create the expire date (yyyymm)


        SqlTransaction transaction;
        Connection.Open(); //open connection to database
        transaction = Connection.BeginTransaction(); //transaction startpoint

        string SqlQuery = "INSERT INTO cardPaymentTable VALUES(@cardNumber,@cardType,@cardHolder,";
        SqlQuery = SqlQuery + "@date, @cvc, @user);"; //add new record info

        try
        {
            SqlCommand cardCmd = new SqlCommand(SqlQuery, Connection, transaction);
            SqlCommand userCmd = new SqlCommand((string)Session["query"], Connection, transaction);

            cardCmd.Parameters.AddWithValue("@cardNumber", creditCardNumberBox.Text);
            cardCmd.Parameters.AddWithValue("@cardType", cardTypeList.SelectedValue);
            cardCmd.Parameters.AddWithValue("@cardHolder", cardHolderBox.Text);
            cardCmd.Parameters.AddWithValue("@date", expiry);
            cardCmd.Parameters.AddWithValue("@cvc", cvcBox.Text);
            cardCmd.Parameters.AddWithValue("@user", Request.QueryString["userName"]); //fill the commandtext with parameters

            cardCmd.ExecuteNonQuery(); //execute the queries
            userCmd.ExecuteNonQuery();

            transaction.Commit();

            //EduLogger.logActivity(User.Identity.Name, "add user", HttpContext.Current.Request.Url.AbsoluteUri);
        }
        catch (SqlException er)
        {
            transaction.Rollback();
            System.Web.Security.Membership.DeleteUser(Request.QueryString["userName"], true);
            Response.Redirect("RegisterControl.aspx");
        }
        Connection.Close(); //close connection to database
        Response.Redirect("HomeScreen.aspx"); //redirect to homepage
    }
}